package cn.zhuangcloud.word;

import cn.zhuangcloud.word.object.Unit;
import com.itextpdf.text.*;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.html.simpleparser.StyleSheet;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ReportCreator {

    private Configuration configuration = new Configuration();

    /**
     * the traditional io way
     *
     * @param filename
     * @return
     * @throws IOException
     */
    public static byte[] file2ByteArray(String filename) throws IOException {
        File f = new File(filename);
        if (!f.exists()) {
            throw new FileNotFoundException(filename);
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(f));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            bos.close();
        }
    }

    public void createWord(Unit[] units) {
        configuration.setDefaultEncoding("UTF-8");
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            dataMap.put("units", units);
            configuration.setDirectoryForTemplateLoading(new File("D:/wordcreater/template"));
            //configuration.setClassForTemplateLoading(this.getClass(), "/template"); // FTL文件所存在的位置
            Template template = configuration.getTemplate("report.ftl");

            File outFile = new File("D:/temp/report.html");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
            template.process(dataMap, out);
            out.close();
            html2Word("D:/temp/report.html", "D:/temp/report.doc");
            //htmlFile2PdfFile("D:/temp/report.html","D:/temp/report.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void html2Word(String htmlPath, String wordPath) throws Exception {
        //word内容
        byte b[] = file2ByteArray(htmlPath);
        ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
        POIFSFileSystem poifs = new POIFSFileSystem();
        poifs.getRoot().createDocument("WordDocument", bais);
        //输出文件
        OutputStream ostream = new FileOutputStream(wordPath);
        poifs.writeFilesystem(ostream);
        bais.close();
        ostream.close();
    }

    @Deprecated
    public void htmlFile2PdfFile(String filePath, String pdfPath) {
        Document document = new Document();
        try {
            StyleSheet st = new StyleSheet();
            st.loadTagStyle("body", "display", "flex");
            st.loadTagStyle("body", "justify-content", "center");
            st.loadStyle("choice", "list-style-type", "upper-alpha");
            st.loadStyle("judge", "color", "red");
            PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
            document.open();
            ArrayList p = (ArrayList) HTMLWorker.parseToList(new FileReader(filePath), st);
            for (Object aP : p) {
                document.add((Element) aP);
            }
            document.close();
            System.out.println("文档创建成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Deprecated
    public void htmlString2PdfFile(String htmlCode, String pdfPath) {
        Document doc = new Document(PageSize.A4);
        try {
            PdfWriter.getInstance(doc, new FileOutputStream(pdfPath));
            doc.open();
            // 解决中文问题
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
            Paragraph t = new Paragraph(htmlCode, FontChinese);
            doc.add(t);
            doc.close();
            System.out.println("文档创建成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}